class TTSoundManager {
    private static _instance:TTSoundManager = null;
    private _tt:any;
    private InnerSoundContext;//背景音乐上下文
    private _isPlay:boolean = false;//是否在播放
    private _swBGM:boolean = true;
    private _swAudio:boolean = true;
    // private InnerAudioContext;//音效上下文
    constructor()
    {
        if(!this._tt)
        {
            this._tt = window['tt'];
        }
        if(!this.InnerSoundContext && this._tt)
        {
            this.InnerSoundContext = this._tt.createInnerAudioContext();
        }
        // if(!this.InnerAudioContext && this._tt)
        // {
        //     this.InnerAudioContext = this._tt.createInnerAudioContext();
        // }
    }

    public static instance():TTSoundManager
    {
        if(!this._instance)
        {
            this._instance = new TTSoundManager();
        }
        return this._instance;
    }

    public swBGM(){
		this._swBGM = !this._swBGM;
		if(this.InnerSoundContext){
			this._swBGM?this.goOnBgm():this.stopBgm();
		}
		return this._swBGM;
	}

    public goOnBgm()
    {
        let ctx = this.InnerSoundContext;
        let src = ctx.src;
        ctx.play();
        ctx.onPlay(() => {
            this._isPlay = true;
            // LogUtil.log(`${src} is going on`);
        });
        ctx.onError((res) => {
            LogUtil.log(res.errMsg);
        })
    }

    public stopBgm()
    {
        if(this.InnerSoundContext)
        {
            let ctx = this.InnerSoundContext;
            ctx.pause();
            // LogUtil.log(`bgm is paused`);
        }
    }

	public swAudio(){
		this._swAudio = !this._swAudio;
		return this._swAudio;
	}

	public get isBGMPlay(){
		return this._swBGM;
	}
	
	public get isAudioPlay(){
		return this._swAudio;
	}

    public playSound(name:string, isLoop:boolean = true)
    {
        let tt = this._tt;
        if(tt && this.InnerSoundContext)
        {
            let ctx = this.InnerSoundContext;
            let src = GameConst.soundURL + name + '.mp3';
            ctx.src = src;
            ctx.loop = isLoop;
            ctx.play();
            ctx.onPlay(() => {
                this._isPlay = true;
                // LogUtil.log(`${name} is playing`);
            });
            ctx.onError((res) => {
                LogUtil.log(res.errMsg);
            })
        }
    }

    public playAudio(name:string, isLoop:boolean = false)
    {
        if(this._swAudio)
        {
            let ctx = this._tt.createInnerAudioContext();
            let src = GameConst.soundURL + name + '.mp3';
            ctx.src = src;
            ctx.isLoop = isLoop;
            ctx.play();
            ctx.onPlay(() => {
                this._isPlay = true;
                // LogUtil.log(`${name} is playing`);
            });
            ctx.onError((res) => {
                LogUtil.log(res.errMsg);
            })
            ctx.onEnded(()=>{
                ctx.destroy()
            })
        }
    }
}